<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/12/1
 * Time: 16:05
 */
namespace app\common\widget\weixin;

use app\common\config\weixin_config;
use app\common\helper\appmenu_helper;
use app\common\helper\company_helper;
use app\common\helper\material_helper;
use app\common\helper\open_card_helper;
use app\common\helper\setting_helper;

class material_widget
{
    protected $company_id;
    protected $open_card_id;
    protected $appmenu_key = array();
    protected $appid;
    protected $appsecret;
    protected $access_token;

    public function __construct()
    {
        $this->open_card_id   = open_card_helper::get_open_card_id();
        $this->company_id     = company_helper::get_company_id();

        $appmenu_key = setting_helper::get_setting_info('appmenu_key');
        if ($appmenu_key) {
            $this->appmenu_key = unserialize($appmenu_key);

            $this->appid        = $this->appmenu_key['appid'];
            $this->appsecret    = $this->appmenu_key['appsecret'];
            $this->access_token = $this->appmenu_key['access_token'];
        }
        //var_dump($this->open_card_id,$this->company_id,$appmenu_key,222);

    }

    /**
     * 处理永久素材中的图片
     * @param $content
     * @param $res_id
     * @return mixed
     */
    public function upload_weixin_img($content, $res_id)
    {
        $img = array();
        preg_match_all('\'<img[^>]*?>\'', $content, $img);

        // 如果没有图片信息 直接返回原内容
        if (!isset($img[0]) || !$img[0]) {
            return array('info'=>'ok', 'content'=>$content);
        }

        //dump($img);
        // 如果存在图片，取出图片内容，进行上传
        $pattern ='<img.*?src="(.*?)".*?>';

        foreach ($img[0] as $k=>$v) {
            $html = $v;
            preg_match($pattern, $html, $matches);

            if ($matches[1]) {
                $per_img_src = $matches[1];
                if (strpos($per_img_src, SITE_URL) === false && strpos($per_img_src, '/storage/upload') === false) {
                    return array('info'=>'内容中含有外链图片，不能同步');
                }

                //var_dump($k, __FUNCTION__, __LINE__);

                // 在关联表创建对应关系
                $filter = array(
                    //'material_id'    => $res_id,
                    'material_id >='    => 1,
                    'old_url'   => $per_img_src
                );
                //var_dump($k, $filter, __LINE__);
                $info = material_helper::get_material_img_info($filter);

                //var_dump($k, $info, __LINE__);

                $time_limit = 0;
                if ($info) {
                    // 找到该图片，且时间间隔不太大时，用此图
                    $tmp_time = time() - strtotime($info['add_time']);
                    if ($tmp_time < 60*60*3) {
                        $time_limit = 1;
                    }
                }

                if ($info && $time_limit == 1) {
                    $content = str_replace($per_img_src, $info['new_url'], $content);

                } else {
                    $matche_str = $per_img_src;

                    //var_dump(SITE_URL);exit;
                    // 进行图片路径替换
                    $str = str_replace(array('http://wx.com', 'http://www.wx.com'), array('', ''), $per_img_src);
                    $str = str_replace(array(SITE_URL, '/storage/upload'), array('', ''), $str);

                    // ueditor中的图下，例如
                    // http://wx.com/js/ueditor1_4_3_3/themes/default/images/spacer.gif
                    if (strpos($str, '/js/') !== false && strpos($str, '/js/') === 0) {
                        $str = ROOT_PATH.$str;
                    } else {
                        $str = UPLOAD_PATH.$str;
                    }

                    //dump(SITE_URL, $str, __FUNCTION__, __LINE__);exit;
                    // 上传图片
                    $data = array(
                        'media' => new \CURLFile($str),
                    );
                    $url  = str_replace('{ACCESS_TOKEN}', $this->access_token, weixin_config::$add_news_content_img_url);
                    $result = h_curl($url, $data, 1);
                    //dump($result, __FUNCTION__, __LINE__);

                    // 替换文件路径,改变原内容
                    if (isset($result['errcode']) && in_array($result['errcode'], array('42001', '40001', '41001'))) {
                        $this->check_app_params();

                        $url  = str_replace('{ACCESS_TOKEN}', $this->access_token, weixin_config::$add_news_content_img_url);
                        $result = h_curl($url, $data, 1);
                    }

                    if (isset($result['errcode']) && in_array($result['errcode'], array('42001', '40001', '41001'))) {
                        return array('info'=>'内容中的部分图片同步失败，请检查图片后重新再试 '.$result['errcode'].' '.$result['errmsg'].' '.$per_img_src);
                    }

                    // 失败后再试一次
                    if (!isset($result['url']) || !$result['url']) {
                        $result = h_curl($url, $data, 1);
                    }

                    if (isset($result['errcode']) && in_array($result['errcode'], array('42001', '40001', '41001'))) {
                        return array('info'=>'内容中的部分图片同步失败，请检查图片后重新再试again '.$result['errcode'].' '.$result['errmsg'].' '.$per_img_src);
                    }

                    if (!isset($result['url']) || !$result['url']) {
                        return array('info'=>'上传图文中的图片失败 '.$result['errcode'].' '.$result['errmsg'].' id:'.$res_id.' '.$str.' '.$per_img_src);
                    }

                    //an_dump($result);
                    $new_url = $result['url'];
                    $data = array(
                        'material_id'   => $res_id,
                        'old_url'       => $matche_str,
                        'new_url'       => $new_url
                    );
                    material_helper::add_material_img_relation($data);
                    $content = str_replace($per_img_src, $new_url, $content);
                }

                //var_dump(__FUNCTION__, __LINE__);
            }
        }

        return array('info'=>'ok', 'content'=>$content);
    }

    /**
     * 删除永久素材
     * @param string $media_id
     * @return mixed
     */
    public function permanent_del_media($media_id)
    {
        if (!$media_id) {
            return '未知素材';
        }

        $data = array(
            'media_id' => $media_id,
        );
        $data = decode_unicode(json_encode($data));

        $url  = str_replace(array('{ACCESS_TOKEN}'), array($this->access_token), weixin_config::$del_news_url);
        $res  = h_curl($url, $data, 1);
        if (isset($res['errmsg']) && $res['errmsg'] != 'ok') {
            // 如果accesss_token失效，重新发送一次
            if (in_array($res['errcode'], array('42001', '40001', '41001'))) {
                $check_flag = $this->check_app_params();
                if ($check_flag) {
                    return $check_flag;
                }

                $url = str_replace(array('{ACCESS_TOKEN}'), array($this->access_token), weixin_config::$del_news_url);
                $res = h_curl($url, $data, 1);
            }
        }

        //dump($res);
        if (isset($res['errmsg']) && $res['errmsg'] != 'ok') {
            if (array_key_exists($res['errcode'], weixin_config::$err_code)) {
                return weixin_config::$err_code[$res['errcode']];
            }

            return '回复失败'.$res['errcode'];
        }

        return 'ok';
    }


    /**
     * 检查并更新appid appsecret accesstoken
     * @return string
     */
    private function check_app_params()
    {
        $access_token = appmenu_helper::get_access_token_new($this->appid, $this->appsecret);
        if (!$access_token) {
            return '获取凭证失败，请检查授权信息';
        }

        $this->appmenu_key['access_token'] = $access_token;
        $this->access_token = $access_token;
        setting_helper::update_setting_info('appmenu_key', serialize($this->appmenu_key));

        return '';
    }

    /**
     * 处理永久素材中的视频
     * @param $content
     * @param $res_id
     * @return mixed
     */
    public function fix_content_video($content, $res_id)
    {
        // 上传永久图文素材之前，需要匹配qq视频，按要求转换成对应的格式。
        $video_iframe = array();
        // 腾讯视频匹配
        $qq_preg = '/<iframe class="qq_video_iframe" data-vid="(.*?)".*?><\/iframe>/';
        // 微信要求的格式（没有明文要求，审查源代码发现的）
        $qq_weixin_html = '<iframe class="video_iframe" style="z-index:1;" height="375" width="500" frameborder="0" src="https://v.qq.com/iframe/preview.html?vid={VID}&amp;width=500&amp;height=375&amp;auto=0" allowfullscreen=""></iframe>';

        preg_match_all($qq_preg, $content, $video_iframe);
        if (isset($video_iframe[1]) && $video_iframe[1]) {
            foreach ($video_iframe[1] as $k=>$v) {
                //an_dump($v);
                $per_qq_weixin_html = str_replace('{VID}', $v, $qq_weixin_html);

                $content = str_replace($video_iframe[0][$k], $per_qq_weixin_html, $content);
            }
        }

        //dump($video_iframe);
        return $content;
    }

    /**
     * 上传永久素材-多媒体
     * @param  array $params
     * @return mixed
     */
    public function permanent_media_upload($params)
    {
        // 媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
        $type       = isset($params['type']) ? $params['type'] : '';
        // 素材本地路径
        $file_path  = isset($params['file_path']) ? $params['file_path'] : '';

        if (!$type) {
            return '类型不能为空';
        }
        if (!$file_path) {
            return '多媒体文件不能为空';
        }

        // 图片路径处理
        if (strpos($file_path, SITE_URL)) {
            $file_path = str_replace(SITE_URL, '', $file_path);
        }
        if (strpos($file_path, '/storage/upload')) {
            $file_path = str_replace('/storage/upload', '', $file_path);
        }
        if (strpos(UPLOAD_PATH, $file_path) === false) {
            $file_path = UPLOAD_PATH.'/'.ltrim($file_path, '/');
        }

        if (!file_exists($file_path)) {
            return '多媒体文件不存在';
        }

        $tmp_image_info = getimagesize($file_path);
        $tmp_image_type = '';
        if (isset($tmp_image_info['mime'])) {
            $tmp_image_type = $tmp_image_info['mime'];
        }
        $tmp_image_name = basename($file_path);
        $data = array("media"  => new \CURLFile($file_path, $tmp_image_type, $tmp_image_name));
        //$data = array("media"  => "@".$file_path);
        $upload_url = str_replace(array('{ACCESS_TOKEN}', '{TYPE}'), array($this->access_token, $type), weixin_config::$add_material_url);
        $res = h_curl($upload_url, $data, 1);

        if (isset($res['errmsg']) && $res['errmsg'] != 'ok') {
            // 如果accesss_token失效，重新发送一次
            if (in_array($res['errcode'], array('42001', '40001', '41001'))) {
                $check_flag = $this->check_app_params();
                if ($check_flag) {
                    return $check_flag;
                }

                $upload_url = str_replace(array('{ACCESS_TOKEN}', '{TYPE}'), array($this->access_token, $type), weixin_config::$add_material_url);
                $res = h_curl($upload_url, $data, 1);
            }
        }

        if (isset($res['errmsg']) && $res['errmsg'] != 'ok') {
            if (array_key_exists($res['errcode'], weixin_config::$err_code)) {
                return weixin_config::$err_code[$res['errcode']];
            }

            return '回复失败'.$res['errcode'];
        }

        return $res;
    }

    /**
     * 上传永久图文消息素材
     * @param array $param
     * @return string|multitype:string
     */
    public function permanent_upload_news($param)
    {
        $data = array(
            'articles' => array()
        );

        if (!is_array($param)) {
            return '上传信息有误';
        }

        foreach ($param as $k=>$v) {

            if (!isset($v['title'])) {
                return 'title缺失';
            }

            if (empty($v['title'])) {
                return '标题不能为空';
            }

            if (!isset($v['thumb_media_id'])) {
                return 'thumb_media_id缺失';//永久封面图media_id
            }

            if (empty($v['thumb_media_id'])) {
                return '图文封面不能为空';
            }

            if (!isset($v['author'])) {
                return 'author缺失';
            }

            if (!isset($v['digest'])) {
                return 'digest缺失';
            }

            if (!isset($v['show_cover_pic'])) {
                return 'show_cover_pic缺失';//是否显示封面
            }

            if (!isset($v['content'])) {
                return 'content缺失';
            }
            if (empty($v['content'])) {
                return '内容不能为空';
            }
            //$param[$k]['content'] = '<p>1234</p>';
            //$param[$k]['content'] .= '<iframe class="video_iframe" style="   z-index:1; " height="375" width="500" frameborder="0" src="https://v.qq.com/iframe/preview.html?vid=t0020f6znwt&amp;width=500&amp;height=375&amp;auto=0" allowfullscreen=""></iframe>';

            if (!isset($v['content_source_url'])) {
                return 'content_source_url缺失';
            }
        }

        $data['articles'] = $param;

        //an_dump($data);
        //exit;
        $data = decode_unicode(json_encode($data));
        $url  = str_replace('{ACCESS_TOKEN}', $this->access_token, weixin_config::$add_news_url);
        $res  = h_curl($url, $data, 1);

        h_curl($res, __FILE__.__LINE__);
        if (isset($res['errmsg']) && $res['errmsg'] != 'ok') {

            // 如果accesss_token失效，重新发送一次
            if (in_array($res['errcode'], array('42001', '40001', '41001'))) {
                $check_flag = $this->check_app_params();
                if ($check_flag) {
                    return $check_flag;
                }

                $url  = str_replace('{ACCESS_TOKEN}', $this->access_token, weixin_config::$add_news_url);
                $res = h_curl($url, $data, 1);
            }
        }
        h_curl($res, __FILE__.__LINE__);
        if (isset($res['errmsg']) && $res['errmsg'] != 'ok') {
            if (array_key_exists($res['errcode'], weixin_config::$err_code)) {
                return weixin_config::$err_code[$res['errcode']];
            }

            return '请求失败'.$res['errcode'];
        }

        return array('info'=>'ok', 'media_id'=>$res['media_id']);
    }

    /**
     * 更新永久图文消息素材
     * @param array $param
     * @param array $media_id
     * @param array $index
     * @return mixed
     */
    public function permanent_update_news($param, $media_id, $index = 0)
    {
        $data = array(
            'media_id'  => $media_id,
            'index'     => $index,
            'articles'  => array()
        );

        if (!$media_id) {
            return '请传递要修改的media_id';
        }

        if (!is_array($param)) {
            return '要修改的图文信息有误';
        }

        if (!isset($param['title'])) {
            return 'title缺失';
        }

        if (empty($param['title'])) {
            return '标题不能为空';
        }

        if (!isset($param['thumb_media_id'])) {
            return 'thumb_media_id缺失';//永久封面图media_id
        }

        if (empty($param['thumb_media_id'])) {
            return '图文封面不能为空';
        }

        if (!isset($param['author'])) {
            return 'author缺失';
        }

        if (!isset($param['digest'])) {
            return 'digest缺失';
        }

        if (!isset($param['show_cover_pic'])) {
            return 'show_cover_pic缺失';//是否显示封面
        }

        if (!isset($param['content'])) {
            return 'content缺失';
        }
        if (empty($param['content'])) {
            return '内容不能为空';
        }
        //$param[$k]['content'] = '<p>1234</p>';
        //$param[$k]['content'] .= '<iframe class="video_iframe" style="   z-index:1; " height="375" width="500" frameborder="0" src="https://v.qq.com/iframe/preview.html?vid=t0020f6znwt&amp;width=500&amp;height=375&amp;auto=0" allowfullscreen=""></iframe>';

        if (!isset($param['content_source_url'])) {
            return 'content_source_url缺失';
        }

        $data['articles'] = $param;

        //an_dump($data);
        //exit;
        $data = decode_unicode(json_encode($data));
        $url  = str_replace('{ACCESS_TOKEN}', $this->access_token, weixin_config::$update_news_url);
        $res  = h_curl($url, $data, true);

        if (isset($res['errcode']) && $res['errcode'] != 0) {

            // 如果accesss_token失效，重新发送一次
            if (in_array($res['errcode'], array('42001', '40001', '41001'))) {
                $check_flag = $this->check_app_params();
                if ($check_flag) {
                    return $check_flag;
                }

                $url  = str_replace('{ACCESS_TOKEN}', $this->access_token, weixin_config::$update_news_url);
                $res = h_curl($url, $data, true);
            }
        }

        if (isset($res['errcode']) && $res['errcode'] != 0) {
            if (array_key_exists($res['errcode'], weixin_config::$err_code)) {
                return weixin_config::$err_code[$res['errcode']].' '.$res['errcode'];
            }

            return '请求失败 '.$res['errcode'];
        }

        return array('info'=>'ok');
    }

    /**
     * 群发前上传图文消息素材
     * @param array $param
     * @return string|multitype:string
     */
    public function upload_news($param)
    {
        $data = array(
            'articles' => array()
        );

        if (!is_array($param)) {
            return '上传信息有误';
        }

        foreach ($param as $k=>$v) {

            if (!isset($v['title'])) {
                return 'title缺失';
            }

            if (empty($v['title'])) {
                return '标题不能为空';
            }

            if (!isset($v['thumb_media_id'])) {
                return 'thumb_media_id缺失';//永久封面图media_id
            }

            if (empty($v['thumb_media_id'])) {
                return '图文封面不能为空';
            }

            if (!isset($v['author'])) {
                return 'author缺失';
            }

            if (!isset($v['digest'])) {
                return 'digest缺失';
            }

            if (!isset($v['show_cover_pic'])) {
                return 'show_cover_pic缺失';//是否显示封面
            }

            if (!isset($v['content'])) {
                return 'content缺失';
            }
            if (empty($v['content'])) {
                return '内容不能为空';
            }
            //$param[$k]['content'] = '<p>1234</p>';
            //$param[$k]['content'] .= '<iframe class="video_iframe" style="   z-index:1; " height="375" width="500" frameborder="0" src="https://v.qq.com/iframe/preview.html?vid=t0020f6znwt&amp;width=500&amp;height=375&amp;auto=0" allowfullscreen=""></iframe>';

            if (!isset($v['content_source_url'])) {
                return 'content_source_url缺失';
            }
        }

        $data['articles'] = $param;

        //an_dump($data);
        //exit;
        $data = decode_unicode(json_encode($data));
        $url  = str_replace('{ACCESS_TOKEN}', $this->access_token, weixin_config::$uploadnews_url);
        $res  = curl($url, $data, true);

        if (isset($res['errmsg']) && $res['errmsg'] != 'ok') {

            // 如果accesss_token失效，重新发送一次
            if (in_array($res['errcode'], array('42001', '40001', '41001'))) {
                $check_flag = $this->check_app_params();
                if ($check_flag) {
                    return $check_flag;
                }

                $url  = str_replace('{ACCESS_TOKEN}', $this->access_token, weixin_config::$uploadnews_url);
                $res = h_curl($url, $data, true);
            }
        }

        if (isset($res['errmsg']) && $res['errmsg'] != 'ok') {
            if (array_key_exists($res['errcode'], weixin_config::$err_code)) {
                return weixin_config::$err_code[$res['errcode']];
            }

            return '请求失败'.$res['errcode'];
        }

        return array('info'=>'ok', 'media_id'=>$res['media_id']);
    }


}